<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="profileObj.photo"
            @click="selectPhotoFn"
          />
          <input
            multiple
            type="file"
            hidden
            ref="photo"
            @change="uploadPhotoFn"
          />
        </template>
      </van-cell>
      <van-cell
        @click="isDialogShow = true"
        title="名称"
        is-link
        :value="profileObj.name"
      />
      <van-cell
        title="性别"
        is-link
        :value="profileObj.gender === 1 ? '男' : '女'"
      />
      <van-cell
        @click="isPopupShow = true"
        title="生日"
        is-link
        :value="profileObj.birthday"
      />
    </van-cell-group>
    <van-dialog
      v-model="isDialogShow"
      title="更新名称"
      show-cancel-button
      :before-close="onDialogBeforeCloseFn"
    >
      <van-field
        v-model.trim="username"
        placeholder="请输入要修改的名称"
        v-focu
      >
      </van-field>
    </van-dialog>
    <van-popup
      v-model="isPopupShow"
      position="bottom"
      :style="{height: '50%'}"
          round>
      <van-datetime-picker
        v-model="current"
        :min-date="min"
        :max-date="max"
        title="选择年月日"
        type="date"
        @confirm="onCanfirmFn"
        @cancel="onCancelFn"
      ></van-datetime-picker>
    </van-popup>
  </div>
</template>

<script>
import {
  getUserProfileAPI,
  updateUserPhotoAPI,
  updateUserProfilerAPI
} from '@/api/user'
// import { filter } from 'vue/types/umd'
import { Notify, Toast } from 'vant'
import moment from 'moment'
export default {
  name: 'UserEdit',
  data () {
    return {
      isDialogShow: false,
      isPopupShow: false,
      profileObj: {},
      username: '',
      min: new Date(2000, 3, 29),
      max: new Date(),
      current: false
    }
  },
  async created () {
    const resp = await getUserProfileAPI()
    this.profileObj = resp.data
    this.current = new Date(resp.data.birthday)
  },
  methods: {
    // 点击图片后替换
    selectPhotoFn () {
      // 用js的方式触发文件域，打开图片
      this.$refs.photo.click()
    },
    // 上传图片，替换掉之前的
    async uploadPhotoFn (e) {
      // 解构
      const { 0: file } = e.target.files
      const { name, size } = file
      const regexp = /\.(png|jpe?gif|webp)$/i
      if (regexp.test(name)) {
        Toast.fail('请选择图片作为图像上传')
        return
      }
      if (size / 1024 / 1024 > 2) {
        Toast.fail('图片大小不能超过2M')
        return
      }

      // 拿到上传的文件对象
      const form = new FormData()
      form.append('photo', e.target.files[0])
      const resp = await updateUserPhotoAPI({
        form: form
      })
      // 更新头像，把后台返回的头像地址覆盖一下
      this.profileObj.photo = resp.data.photo
    },
    async onDialogBeforeCloseFn (action, done) {
      if (action === 'cancel') {
        done()
        return
      }
      if (!this.username) {
        Notify({ type: 'warning', message: '名称不能为空' })
        done(false)
      } else {
        await updateUserProfilerAPI({
          name: this.username,
          birthday: this.profileObj.birthday
        })
        // console.log(resp)
        this.profileObj.name = this.username
        this.username = ''
        done()
      }
    },
    async onCanfirmFn (value) {
      const str = moment(value).format('YYYY-MM-DD')
      await updateUserProfilerAPI({
        name: this.profileObj.name,
        birthday: str
      })
      this.profileObj.birthday = str
      this.isPopupShow = false
    },
    //
    onCancelFn () {
      this.isPopupShow = false
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
